import 'dart:convert';

import 'package:flutter_provider_demo/commons/http_client.dart';
import 'package:flutter_provider_demo/commons/result.dart';
import 'package:flutter_provider_demo/data/services/api/api.dart';
import 'package:flutter_provider_demo/data/services/api/models/api_response.dart';
import 'package:flutter_provider_demo/data/services/api/models/catalog/catalog_response.dart';

class CatalogApiClient {
  final HttpClient _httpClient;

  CatalogApiClient({HttpClient? httpClient})
      : _httpClient = httpClient ?? HttpClient();

  Future<Result<List<CatalogResponse>>> getCatalog(int page) async {
    final response = await _httpClient.get(
      Api.catalog + '?page=$page',
      headers: {'Content-Type': 'application/json'},
    );
    if (response.statusCode == 200) {
      Map<String, dynamic> json = jsonDecode(response.body);
      ApiResponse<List<CatalogResponse>> apiResponse = ApiResponse.fromJson(json, (data) {
        if (data != null && data is List) {
          return data.map((e) => CatalogResponse.fromJson(e)).toList();
        } else {
          return [];
        }
      });
      if (apiResponse.code == 0) {
        return Result.ok(apiResponse.data!);
      } else {
        return Result.error(Exception(apiResponse.message));
      }
    } else {
      return Result.error(Exception("Find catalog error, status code: ${response.statusCode}"));
    }
  }
}
